package com.itbaizhan.cxpt.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.itbaizhan.cxpt.common.Result;
import com.itbaizhan.cxpt.entity.CxptBz;
import com.itbaizhan.cxpt.entity.FileDesc;
import com.itbaizhan.cxpt.mapper.FileDescMapper;
import com.itbaizhan.cxpt.service.PdfAnalyzeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@RestController
@RequestMapping("/api/standard")
public class ExcelExportController {

    @Autowired
    private FileDescMapper fileDescMapper;

    /**
     * 导出分析结果为Excel
     * @param response HTTP响应对象
     */
    @GetMapping("/export-excel/{id}")
    public void exportExcel(@PathVariable Long id, HttpServletResponse response) throws IOException {
        List<FileDesc> fileDescs = fileDescMapper.findByFileIdAndStatus(id);
        if (!CollectionUtils.isEmpty(fileDescs)) {

            // 创建ExcelWriter对象
            ExcelWriter writer = ExcelUtil.getWriter(true);

            // 设置列宽
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 40);
            writer.setColumnWidth(2, 20);
            writer.setColumnWidth(3, 15);

            // 设置表头
            writer.addHeaderAlias("a100", "国标号");
            writer.addHeaderAlias("a298", "国标名称");
            writer.addHeaderAlias("fileResult", "描述");
            writer.addHeaderAlias("desc", "状态");

            // 处理状态显示
            fileDescs.forEach(fileDesc -> {
                if (fileDesc.getFileStatus() != null) {
                    fileDesc.setDesc(fileDesc.getFileStatus() == 1 ? "符合" : "不符合");
                }
            });

            // 隐藏不需要的字段
            writer.setOnlyAlias(true);

            // 写入数据
            writer.write(fileDescs, true);

            // 设置响应头
            String fileName = "国标分析结果_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

            // 写入响应输出流
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        }
    }
}